
import { useUserStore } from '@/store'


const navigateToInterceptor = {
	invoke({ url }) {
		console.log(url)
		const path = url.split('?')[0]
		const { token } = useUserStore()
		const { noLogin, loginPage, homePahe } = uni.$config
		
		if(!url) {
			uni.navigateTo({ url: homePahe })
			return false
		}
		
		if(token && loginPage === path) return false
		
		if(!noLogin.includes(path)) {
			if(token) return true
			// 没有登录，跳转到登录页面
			const redirectRoute = `${loginPage}?redirect=${encodeURIComponent(url)}`
			uni.navigateTo({ url: redirectRoute })
			return false
		}
		return true
	}
}

export const routeInterceptor = {
	install() {
		uni.addInterceptor('switchTab', navigateToInterceptor)
		uni.addInterceptor('navigateTo', navigateToInterceptor)
		uni.addInterceptor('reLaunch', navigateToInterceptor)
		uni.addInterceptor('redirectTo', navigateToInterceptor)
  }
}
